package com.valuegroup.smarttodo.ui.programme.goals.detail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.Goals;
import com.valuegroup.smarttodo.data.vo.GoalsEventVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.CustomTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddActivity;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QucikAddInputCheckRule;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddEditorCallback;
import com.valuegroup.smarttodo.ui.todo.task.qucikadd.QuickAddHolder;
import com.valuegroup.smarttodo.util.AlertUtils;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 目标详情
 */
public class GoalsDetailActivity extends BaseActivity {

    private ItemTouchHelper mItemTouchHelper;
    private GoalsDetailAdapter adapter;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.labHeader)
    CustomTextView labHeader;
    @BindView(R.id.chkFinish)
    AppCompatCheckBox chkFinish;
    @BindView(R.id.labTitle)
    ClickableTextView labTitle;
    @BindView(R.id.labTitleEdit)
    MultilineEditText labTitleEdit;
    @BindView(R.id.headerShadow)
    View headerShadow;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.labEditDt)
    TextView labEditDt;
    @BindView(R.id.btnStar)
    AppCompatCheckBox btnStar;
    @BindView(R.id.rootLayout)
    CoordinatorLayout rootLayout;

    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Goals DATA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goals_detail);
        ButterKnife.bind(this);

        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getGoalsService().getGoalsDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(this, R.string.not_found_record);
            finish();
            return;
        }

        initView();
        initData();
    }

    private void initData() {

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getGoalsService().getDefaultGoals();
            // 清空默认标签,避免无效保存
            DATA.setTitle("");

            labTitleEdit.setText("");
            labTitleEdit.setVisibility(View.VISIBLE);
            labTitle.setVisibility(View.GONE);

            // 动态给EditText获得焦点并弹起软键盘
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            labTitleEdit.setFocusable(true);
            labTitleEdit.setFocusableInTouchMode(true);
            labTitleEdit.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(labTitleEdit, 0);

            // 新增状态需要屏蔽部分按钮
            btnStar.setVisibility(View.GONE);
            labEditDt.setVisibility(View.GONE);
        } else {
            // 新增状态刚保存后,需要重新加载数据
            if (DATA.getId() == null) {
                DATA = ServiceFactory.getInstance().getGoalsService().getGoalsDao().load(DATA_ID);
            }

            btnStar.setVisibility(View.VISIBLE);
            labTitle.setVisibility(View.VISIBLE);
            labEditDt.setVisibility(View.VISIBLE);
            labTitleEdit.setVisibility(View.GONE);

            // 任务主干
            labTitle.setText(DATA.getTitle());
            chkFinish.setChecked(DATA.getIsFinish());
            btnStar.setChecked(DATA.getIsStar());
            labEditDt.setText(String.format(getResources().getString(DATA.getIsFinish() ? R.string.finish_time : R.string.update_time), DateUtils.date2str(DATA.getIsFinish() ? DATA.getFinishDt() : DATA.getUpdatedDt(), DateUtils.F33)));
        }

        // 读取步骤数据
        if (adapter != null) {
            adapter.refreshListData(DATA_ID, false);
        } else {
            adapter = new GoalsDetailAdapter(this, recyclerView, DATA_ID);
            recyclerView.setAdapter(adapter);

            ItemTouchHelper mItemTouchHelper = new ItemTouchHelper(new GoalsDetailTouchHelper(adapter, this));
            mItemTouchHelper.attachToRecyclerView(recyclerView);
        }
    }

    private void initView() {

        // 初始化工具条
        setSupportActionBar(toolbar);
        // 隐藏Toolbar的标题栏
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        btnBack.setColorFilter(ContextCompat.getColor(this, R.color.textHint));

        // 任务主干编辑状态控制
        labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    labTitleEdit.setSelection(labTitleEdit.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(labTitleEdit, 0);

                } else {
                    // 失去焦点
                    labTitle.setVisibility(View.GONE);
                    labTitleEdit.setText(labTitleEdit.getText());
                    labTitleEdit.setVisibility(View.VISIBLE);

                    // 保存标题
                    if (!TextUtils.isEmpty(labTitleEdit.getText())) {
                        boolean isFirst = (DATA_ID == 0);
                        DATA = ServiceFactory.getInstance().getGoalsService().saveGoalTitle(DATA.getId(), labTitleEdit.getText().toString());
                        DATA_ID = DATA.getId();
                        if (isFirst) {
                            initData();
                        }
                    }
                }
            }
        });
        labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    labTitle.setText(v.getText());
                    labTitle.setVisibility(View.VISIBLE);
                    labTitleEdit.setVisibility(View.GONE);
                }
                return true;
            }
        });

        // 任务主干选中状态控制
        chkFinish.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                ServiceFactory.getInstance().getGoalsService().doFinish(DATA.getId(), b);
                if (b) {
                    labTitle.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.textHint));
                    labTitle.getPaint().setStrikeThruText(true);// setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                } else {
                    labTitle.setTextColor(ContextCompat.getColor(getBaseContext(), R.color.textDefault));
                    labTitle.getPaint().setStrikeThruText(false);// setFlags(0);
                }
            }
        });

        btnStar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ServiceFactory.getInstance().getGoalsService().doStar(DATA.getId(), isChecked);
            }
        });

        // 任务步骤
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerView.canScrollVertically(-1)) {
                    headerShadow.setVisibility(View.VISIBLE);
                } else {
                    headerShadow.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 滚动状态变化时回调
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_goal_order, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (DATA_ID == 0) {
            AlertUtils.showToast(this, R.string.need_insert_content);
            return false;
        }

        switch (item.getItemId()) {
            case R.id.m1:
                /*初始化 浮动在键盘上的快捷输入框*/
                QucikAddActivity.openEditor(
                        this,
                        new QuickAddEditorCallback() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSubmit(String content) {
                                if (TextUtils.isEmpty(content)) {
                                    return;
                                }

                                // 新增内容
                                GoalsEventVo item = new GoalsEventVo();
                                item.setGid(DATA_ID);
                                item.setTitle(content.trim());
                                adapter.addItem(adapter.getContentSize(), item);

                                //平滑到新增项
                                recyclerView.smoothScrollToPosition(adapter.getContentSize());
                            }

                            @Override
                            public void onAttached(final ViewGroup rootView) {
                                // 表情(暂时弃用)
                            }
                        },
                        new QuickAddHolder(QuickAddHolder.QuickAddType.EVENT_INSERT),
                        new QucikAddInputCheckRule(120, 2));

                break;
            case R.id.m2:

                QucikAddActivity.openEditorNoRepeat(
                        this,
                        new QuickAddEditorCallback() {
                            @Override
                            public void onCancel() {
                            }

                            @Override
                            public void onSubmit(String content) {
                                if (TextUtils.isEmpty(content)) {
                                    return;
                                }
                                ServiceFactory.getInstance().getGoalsService().multiInsert(DATA_ID, content);
                                initData();
                            }

                            @Override
                            public void onAttached(ViewGroup rootView) {

                            }
                        },
                        new QuickAddHolder(QuickAddHolder.QuickAddType.MULTI_INSERT_FOR_GOALS),
                        new QucikAddInputCheckRule(2000, 2),
                        Gravity.CENTER);
                break;
            case R.id.m3:

                AlertUtils.delOrderDialog(this,
                        String.format(getResources().getString(R.string.alt_del_goal), DATA.getTitle()),
                        (dialog, which) -> {
                            ServiceFactory.getInstance().getGoalsService().delGoal(DATA.getId());
                            finishAfterTransition();
                        });
                break;

        }
        return false;
    }

    @OnClick({R.id.btnBack, R.id.rootLayout, R.id.labTitle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                setCloseParams();
                finishAfterTransition();
                break;

            case R.id.rootLayout:
                break;
            case R.id.labTitle:
                // 头部任务主干点击事件

                labTitleEdit.setText(labTitle.getText());
                labTitleEdit.setVisibility(View.VISIBLE);
                labTitle.setVisibility(View.GONE);

                // 获得焦点
                labTitleEdit.setFocusable(true);
                labTitleEdit.setFocusableInTouchMode(true);
                labTitleEdit.requestFocus();
                break;
        }
    }


    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        initData();
    }
}
